<template>
  <div id="app-box">
  
    <mu-search v-model="searchValue" v-show="showSearchPanel" @click="hideSearchPanel" autofocus placeholder="沙龙关键词搜索">
      <ul class="search-result" style="display:block;">
        <li v-show="activities.length==0&&isActivitySearching" style="text-align:center">正在加载...</li>
        <li v-show="activities==nearestActivities&&!isActivitySearching" style="text-align:center">以下为最近活动列表...</li>
         <li v-show="activities.length==0&&!isActivitySearching&&!isFirst" style="text-align:center">未找到相关活动</li>
        <li v-for="(item,index) in activities" @click="changeActivity(item.id)">
          {{index+1}}、{{item.title}}
        </li>
      </ul>
    </mu-search>
  
    <masker style="border-radius: 2px;">
      <div class="m-img" :style="{backgroundImage: 'url(' + bannerUrl + ')'}"></div>
      <div slot="content" class="m-title">
        {{currentActivityInfo.title}}
        <br/>
        <span class="m-time">{{currentActivityInfo.duration}}</span>
      </div>
    </masker>
    <card style="margin-top:0px!important;">
  
      <div slot="content">
        <div class="content-left">
          <img :src="currentActivityInfo.qrurl" @click="showQR=true" style="box-sizing: border-box;width: 100%;display: block;padding: 10px;">
          <p  style="margin: 0px;font-size: 0.8rem;color: #999;text-align: center;padding: 0px 15px;">参会人员使用
            <span>扫一扫</span>进行验票</p>
        </div>
        <div class="content-right">
          <!-- <p>{{currentActivityInfo.title}}</p> -->
  
          <p class="summary">{{currentActivityInfo.summary}}</p>
          <p>地址：{{currentActivityInfo.address}}</p>
          <p>时间：{{currentActivityInfo.duration}}</p>
          <x-button mini plain @click.native="goSignUp">前往报名</x-button>
          <x-button mini plain @click.native="showSearchPanel=true">重选活动</x-button>
        </div>
      </div>
    </card>
    <div style="height:44px;" class="timeline">
      <sticky :offset="46" :check-sticky-support="false">
  
        <tab :animate="false" @on-index-change="onTabChange">
          <tab-item active-color="tab-check-fail" badge-background="red" badge-color="#fff" :badge-label="checkList.length+''" selected>实时</tab-item>
          <!-- <tab-item active-color="tab-check-success" badge-background="green" badge-color="#fff" badge-label="2">已核票</tab-item> -->
          <tab-item active-color="tab-check-success" badge-background="green" badge-color="#fff" :badge-label="userList.length+''">参会人员</tab-item>
        </tab>
  
      </sticky>
    </div>
    <!--参会用户的签到情况  -->
    <div class="user-check" v-show="tabIndex==1">
      <ul>
        <li v-for="(user,index) in userList" :key="index" :class="(index%2)==1?'item-bg':''">
          {{user.user_name}}
          <span>
            <x-button style="float:right;" mini plain :type="user.sign_in==1?'primary':'warn'">{{user.sign_in==1?"已签到":"未签到"}}</x-button>
          </span>
        </li>
  
      </ul>
    </div>
    <!--实时签到页面 -->
    <div class="live-check" v-show="tabIndex==0">
      <timeline>
        <timeline-item v-for="(item, index)  in checkList" :class="item.type==1?'success-timeline-item':'fail-timeline-item'" :key="index">
          <p class="check-item-title">{{item.user_name}}</p>
          <p>
            <span>{{item.type==1?"核票通过":(item.type==2?"未报名":"报名未付款")}}</span>
            <span>{{dateFormat(item.time)}}</span>
          </p>
        </timeline-item>
      </timeline>
    </div>
    <!-- <p v-for="i in 20">{{i}}</p> -->
    <!--显示二维码弹窗  -->
    <x-dialog v-model="showQR" class="dialog-demo" :scroll="false" :hide-on-blur="true">
      <div class="img-box">
        <img :src="currentActivityInfo.qrurl" style="max-width:100%">
      </div>
      <div @click="showQR=false">
        <span class="vux-close"></span>
      </div>
    </x-dialog>
  </div>
</template>
<script>
import { Search } from 'mint-ui'
import { stringTrim } from 'vux'
import { Divider, Card, Masker, Tab, TabItem, Sticky, XDialog, XButton, Timeline, TimelineItem } from 'vux'
import { dateFormat } from 'vux'

// import { card } from 'muse-ui/src/card/card.vue'
export default {
  name: 'app-box',
  components: {
    "timeline": Timeline,
    "timeline-item": TimelineItem,
    "x-button": XButton,
    "x-dialog": XDialog,
    "sticky": Sticky,
    "tab": Tab,
    "tab-item": TabItem,
    "masker": Masker,
    "card": Card,
    "divider": Divider,
    // 'mt-cell': Cell, Checklist, 'mt-header': Header, 'mt-search': Search
    "mu-search": Search
  },
  data() {
    return {
      showQR: false,
      banner: "/static/banner.jpg",
      currentActivityInfo: {
        id: 0,
        duration: "",
        title: "",
        summary: "",
        qrurl: "",
        url: "",
        address: ''
      },
      userList: [],
      isFirst: true,
      showSearchPanel: false,
      searchValue: '',
      isActivitySearching: false,
      tabIndex: 0,
      checkList: [],
      checkListHttpList: [],
      checkListCancelToken: undefined,
      activities: [],
      nearestActivities:[],
      signInInfos: [
        {
          name: "lkkjzx",
          openid: "asdniasd",
        }
      ],
      activityHttpList: []
    }
  },
  watch: {
    searchValue: function (newValue, oldValue) {
      if(stringTrim(newValue).length==0){
        this.activities=this.nearestActivities;
        return;
      }
      if (stringTrim(newValue) != stringTrim(oldValue)) {
        this.searchActivityList(newValue)
      }
    },
    currentActivityInfo: function (newValue, oldValue) {
      let vm = this;
      vm.checkList = [];
      vm.checkListHttpList.forEach(function (source, index, array) {
        source.cancel('取消签到数据的请求');
        array.splice(index, 1);
      }, this);
      vm.getCheckList();
    }
  },
  computed: {
    bannerUrl() {
      return this.url.static + "/banner.jpg"
    }
  },
  created() {
    this.$on("input", function () {
      console.log(dadas)
    })
  },
  mounted() {
    let vm = this;
    //初始化就显示取消
    document.querySelector(".mint-searchbar-cancel").style.display = "block";
    //点击搜索的取消 隐藏搜索面板
    document.querySelector(".mint-searchbar-cancel").addEventListener("click", function () {
      vm.showSearchPanel = false;
      //  document.querySelector(".mint-search").style.display = 'none' 
    })
    document.querySelector(".mint-search-list").className += " " + "mint-search-list-block";
    document.querySelector(".mint-search-list").addEventListener("click", function () {
      vm.showSearchPanel = false;
    })
    this.changeActivity(0);

  },
  methods: {
    showToast(content) {
      this.$vux.toast.show({
        text: content
      })
    },
    getCheckList() {
      let vm = this;

      let CancelToken = vm.$http.CancelToken;
      let source = CancelToken.source();
      vm.checkListHttpList.push(source)
      vm.$http.get(vm.url.acid + "&do=signintracking&actid=" + vm.currentActivityInfo.id + "&start=" + vm.checkList.length, { cancelToken: source.token }).then(response => {
        let body = response.data;
        //如果不是当前活动的，直接返回
        if (!response.config.url.includes("&actid=" + vm.currentActivityInfo.id + "&")) {
          return;
        }
        if (body.status == "success") {
          console.log(body.data)
          for (let i = body.data.length - 1; i >= 0; i--) {
            let checkItem = body.data[i];
            //更新参会人员信息
            if (checkItem.type == 1) {

              let isExistUser = false;
              for (let j = 0; j < vm.userList.length; j++) {
                let user = vm.userList[j];
                if (user.open_id == checkItem.openid) {
                  isExistUser = true;
                  if(user.sign_in==0){
                    user.sign_in=1;
                     vm.showToast("用户签到成功~~")
                  }
                  break;
                }
              }
              if (!isExistUser) {
                vm.userList.unshift({
                  user_name: checkItem.user_name,
                  open_id: checkItem.openid,
                  sign_in: 1
                })
                vm.showToast("用户签到成功~")
              }
            }
            vm.checkList.unshift(body.data[i])
          }
            vm.getCheckList()
        }
        //出现错误就别一直递归调用了
      
      }, response => {
        if (!response.config.url.includes("&actid=" + vm.currentActivityInfo.id + "&")) {
          return;
        }
        vm.getCheckList()
      }).catch(function (thrown) {
        if (vm.$http.isCancel(thrown)) {
          console.log('Request canceled', thrown.message);
        } else {
          // 处理错误
        }
      });
    },
    dateFormat(timesamp) {
      return dateFormat(new Date(timesamp * 1000), ' HH:mm MM/DD')
    },
    onTabChange(index) {
      this.tabIndex = index;
      console.log(index)
    },
    hideSearchPanel() {
      this.showSearchPanel = false;
    },
    searchActivityList(kw) {
      let vm = this;
      if (vm.isFirst) {
        vm.isFirst = false
      }
      vm.activityHttpList.forEach(function (source, index, array) {
        source.cancel('又有了新请求，取消前面的请求了!');
        array.splice(index, 1);
      }, this);
      vm.activities = [];
      if (kw.length == 0) {
        return;
      }

      vm.isActivitySearching = true;
      let CancelToken = vm.$http.CancelToken;
      let source = CancelToken.source();
      vm.activityHttpList.push(source);

      let query = vm.$http.get(vm.url.acid + "&do=searchActivity&keyword=" + kw, { cancelToken: source.token })
        .then(response => {
          vm.isActivitySearching = false;
          let body = response.data;
          if (body.status == "success") {
            vm.activities = body.data;
          } else {
            vm.$vux.alert.show({
              title: '提示',
              content: '链连接服务器失败'
            })
          }
          // console.log(body)
        }, response => {
          vm.isActivitySearching = false;
          console.log(response)
        }).catch(function (thrown) {
          vm.isActivitySearching = false;
          if (vm.$http.isCancel(thrown)) {
            console.log('Request canceled', thrown.message);
          } else {
            // 处理错误
          }
        });
    },
    changeActivity(actid) {
      let vm = this;
      vm.showSearchPanel = false;
      vm.$vux.loading.show({
        text: '获取活动信息中...'
      })
      vm.$http.get(vm.url.acid + "&do=signin&actid=" + actid).then(response => {
        vm.$vux.loading.hide()
        let body = response.data;
        if (body.status == "success") {
          vm.currentActivityInfo = body.activity;
          vm.userList = body.users;
          vm.nearestActivities=body.nearestActivities;
          vm.activities=body.nearestActivities;

        } else {
          vm.$vux.alert.show({
            title: '提示',
            content: '链连接服务器失败',
          })
        }
        // console.log(body)
      }, response => {
        vm.$vux.loading.hide()
        vm.$vux.alert.show({
          title: '出错提示',
          content: "获取信息失败",
        })
      }).catch(function (thrown) {
        vm.$vux.loading.hide()
        vm.$vux.alert.show({
          title: '出错提示',
          content: thrown.message,
        })

      });

    },
    checkSerachPanelStatus() {
      console.log(this.searchValue)
    },
    goSignUp() {
      window.location.href = this.currentActivityInfo.url;
    }
  }
}
</script> 
<style>
@keyframes alertAnimation {
  0% {
    transform: scale(0.5)
  }

  45% {
    transform: scale(1.25)
  }

  80% {
    transform: scale(0.95)
  }

  100% {
    transform: scale(1)
  }
}

@-webkit-keyframes alertAnimation {
  0% {
    -webkit-transform: scale(0.5)
  }

  45% {
    -webkit-transform: scale(1.25)
  }

  80% {
    -webkit-transform: scale(0.95)
  }

  100% {
    -webkit-transform: scale(1)
  }
}

@-moz-keyframes alertAnimation {
  0% {
    -moz-transform: scale(0.5)
  }

  45% {
    -moz-transform: scale(1.25)
  }

  80% {
    -moz-transform: scale(0.95)
  }

  100% {
    -moz-transform: scale(1)
  }
}
</style>
<style lang="less" scoped>
@import '~vux/src/styles/close';
.dialog-demo {
  .weui-dialog {
    border-radius: 8px;
    padding-bottom: 8px;
  }
  .dialog-title {
    line-height: 30px;
    color: #666;
  }
  .img-box {
    // height: 350px;
    overflow: hidden;
  }
  .vux-close {
    margin-top: 8px;
    margin-bottom: 8px;
  }
}
</style>


<style>
.checked-icon,
.fail-icon {
  width: 1.5rem;
}

.card-padding {
  padding: 15px;
}

.mint-search {

  width: 100vw;
  position: fixed;
  height: 100vh;
  overflow: hidden;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.7);
  animation: alertAnimation .3s ease-in-out 0 1;
  -webkit-animation: alertAnimation .3s ease-in-out 0 1;
  -moz-animation: alertAnimation .3s ease-in-out 0 1;
}

.mint-search-list {
  height: 100vh;
}

body {
  margin: 0px;
  width: 100%;
  padding: 0px;
}

.search-result {
  margin: 0px;
  padding: .5rem 0px;
}

.search-result li {
  padding: 0px .5rem;
  list-style-type: none;
  line-height: 2rem;
  text-align: left;
  background: white;
}

.search-result li:active {
  background-color: #333;
  color: #26a2ff;
}


.content-left {
  float: left;
  width: 40%;
}

.content-right {
  padding: 10px 10px 10px 0px;
  float: left;
  width: 60%;
  box-sizing: border-box;
}

.content-right p {
  margin: .4rem 0;
  line-height: 1.2rem;
  font-size: .8rem;
}
.mint-search-list-block{
  display:block!important;
}

.summary {
  font-size: .8rem;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

.success-timeline-item {
  /* background:rgba(51,255,0,0.5); */
}

.fail-timeline-item {
  color:red;
   /* background:rgba(204,51,0,0.5);  */
}

.live-check ul {
  padding-left: 10px;
  /* margin-top: 0px; */
}

.check-item-title {
  margin: 0px;
}

.user-check li {
  padding: .5rem 1rem;
  overflow: hidden;
  vertical-align: middle;
  /* border-bottom: 1px solid #999; */
}

.user-check ul {
  margin: 0px;
  padding: 0px;
}

.user-check .item-bg {
  background: rgba(0, 0, 0, .05);
}

.tab-check-success {
  color: green !important;
  border-color: green !important;
}

.tab-check-fail {
  color: red !important;
  border-color: red !important;
}

.m-img {
  padding-bottom: 33%;
  display: block;
  position: relative;
  max-width: 100%;
  background-size: cover;
  background-position: center center;
  cursor: pointer;
  border-radius: 2px;
}

.m-title {
  color: #fff;
  text-align: center;
  text-shadow: 0 0 2px rgba(0, 0, 0, .5);
  font-weight: 500;
  font-size: 16px;
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  text-align: center;
  top: 50%;
  transform: translateY(-50%);
}

.m-time {
  font-size: 12px;
  padding-top: 4px;
  border-top: 1px solid #f0f0f0;
  display: inline-block;
  margin-top: 5px;
}
</style>
